package test1;

import test1.pojo.User;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ListSort {
    public static void main(String[] args) {

        List<User> list = new ArrayList<>();
        list.add(new User("张三",12));
        list.add(new User("李四",7));
        list.add(new User("小六",6));
        list.add(new User("王五",17));
        list.add(new User("xiaozhang",null));
//        test1(list);
//        test2(list);
        test3(list);

    }

    private static void test1(List<User> list){
        for (User user : list) {
            System.out.println(user);
        }

        //升序
        Collections.sort(list, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                if (o1.getAge() == null){
                    return -1;
                }

                if (o1.getAge() > o1.getAge()){
                    return 1;
                } else if (o1.getAge() < o2.getAge()) {
                    return -1;
                }else {
                    return 0;
                }
            }
        });
        System.out.println("-----------");
        list.forEach(System.out::println);
    }

    private static void test3(List<User> list){
        for (User user : list) {
            System.out.println(user);
        }

        //升序
        Collections.sort(list, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                if (o1.getAge() == null){
                    return -1;
                }
                return o1.getAge() - o2.getAge();
            }
        });
        System.out.println("-----------");
        list.forEach(System.out::println);
    }

    private static void test2(List<User> list){
        list.forEach(System.out::println);
        list = list.stream()
                .sorted(Comparator.comparing(User::getAge,Comparator.nullsFirst(Comparator.naturalOrder())))
                .collect(Collectors.toList());
        System.out.println("----------------");
        list.forEach(System.out::println);

    }
}
